﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Niti.OrderManage.Application.Contracts;
using Niti.OrderManage.DTO;
using Niti.OrderManage.Eto;
using Niti.OrderManage.OrderManage;
using Niti.OrderManage.OrderManage.Repositories;
using Niti.OrderManage.ToolKits.Base;
using Niti.OrderManage.ToolKits.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.EventBus;
using Volo.Abp.ObjectMapping;
using static Niti.OrderManage.NitiOrderManageConsts;

namespace Niti.OrderManage.Order.Impl
{
    [ApiController]
    [Route("[controller]")]
    [ApiExplorerSettings(GroupName = Grouping.GroupName_v2)]
    public class SupplierService: NitiOrderManageApplicationServiceBase,
         ILocalEventHandler<OrderSupplicerEto>
       // ,ILocalEventHandler<CheckOrderExistsEto>
    {
        private readonly ISupplierRepository _supplierRepository;
        private readonly ILogger _logger;

        public SupplierService(ISupplierRepository supplierRepository,ILogger<SupplierService> logger)
        {
            _supplierRepository = supplierRepository;
            _logger = logger;
        }
       
     
        /// <summary>
        /// 增加供应商
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ServiceResult<string>> InsertSupplierAsync(AddSupplierDto dto)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该供应商
                var entityExist = _supplierRepository.Where(x => x.Code == dto.Code&&x.IsDeleted==false).OrderByDescending(x => x.CreationTime).FirstOrDefault();
                if (entityExist != null)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED + ",已存在该供应商");
                    return result;
                }

                //   var entity = ObjectMapper.Map<AddSupplierDto, Supplier>(dto);
                var entity = new Supplier
                {
                    Code = dto.Code,
                    SName = dto.SName,
                    BeginTime = dto.BeginTime,
                    EndTime = dto.EndTime,
                    ContactName = dto.ContactName,
                    ContactNumber = dto.ContactNumber
                };

                var post = await _supplierRepository.InsertAsync(entity);
                if (post == null)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED);
                    return result;
                }

                result.IsSuccess(ResponseText.INSERT_SUCCESS);

            }
            catch (Exception ex)
            {
               _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.INSERT_FAILED);
            }

            return result;
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ServiceResult> DeleteSupplierAsync(int id)
        {
            ServiceResult result = new ServiceResult();
            try
            {
                var supplier = await _supplierRepository.FindAsync(x=>x.Id==id&&x.IsDeleted==false);
                if (supplier == null)
                {
                    result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("Id", id));
                    return result;
                }

                supplier.IsDeleted = true;
                supplier.DeleteTime = DateTime.Now;
                var entity = await _supplierRepository.UpdateAsync(supplier);
                if (entity != null)
                {
                    result.IsSuccess(ResponseText.DELETE_SUCCESS);
                }
                else
                {
                    result.IsFailed(ResponseText.DELETE_FAILED.FormatWith("Id", id));
                }


            }
            catch (Exception ex)
            {
               _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.DELETE_FAILED);
            }

            return result;
        }
        /// <summary>
        /// 修改供应商
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ServiceResult<string>> UpdateSupplierAsync(int id, SupplierDto dto)
        {
            var result = new ServiceResult<string>();
            try
            {
                var supplier = await _supplierRepository.FindAsync(x=>x.Id==id&&x.IsDeleted==false);
                if (supplier == null)
                {
                    result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("Id", id));
                    return result;
                }

                //var entity = ObjectMapper.Map<SupplierDto, Supplier>(dto);

                #region 映射
                supplier.SName = dto.SName;
                supplier.BeginTime = dto.BeginTime;
                supplier.EndTime = dto.EndTime;
                supplier.ContactName = dto.ContactName;
                supplier.ContactNumber = dto.ContactNumber;
                supplier.UpdateTime = dto.UpdateTime;
                #endregion

                var post = await _supplierRepository.UpdateAsync(supplier);
                if (post == null)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED);
                    return result;
                }

                result.IsSuccess(ResponseText.UPDATE_SUCCESS);

            }
            catch (Exception ex)
            {
               _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.UPDATE_FAILED);
            }
            return result;


        }

        /// <summary>
        /// 根据id查询供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ServiceResult<SupplierDto>> GetSupplierAsync(int id)
        {
            ServiceResult<SupplierDto> result = new ServiceResult<SupplierDto>();
            try
            {
                var entity = await _supplierRepository.GetAsync(x=>x.Id==id&&x.IsDeleted==false);
                if (entity.IsDeleted == true)
                {
                    result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("Id", id));
                    return result;
                }

                result.IsSuccess("ok");
                // var dto = ObjectMapper.Map<Supplier,SupplierDto>(entity);
                var dto = new SupplierDto()
                {
                    Code = entity.Code,
                    SName=entity.SName,
                    BeginTime = entity.BeginTime,
                    EndTime = entity.EndTime,
                    ContactName = entity.ContactName,
                    ContactNumber = entity.ContactNumber
                };
                result.Result = dto;

            }
            catch (Exception ex)
            {
                result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("Id", id));
               _logger.LogError(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">条数</param>
        /// <param name="name">名称</param>
        /// <param name="code">编号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("SupplierList")]
        public async Task<ServiceResult<PagedList<SupplierDto>>> GetSupplierListAsync(int pageIndex=1,int pageSize=10, string name = "",string code="")
        {
            var result = new ServiceResult<PagedList<SupplierDto>>();
            try
            {

                var list = (from suppliers in await _supplierRepository.GetListAsync()
                            where (string.IsNullOrEmpty(name)||suppliers.SName.Contains(name))
                                  && (string.IsNullOrEmpty(code) || suppliers.Code==code)
                                  && suppliers.IsDeleted == false
                            orderby suppliers.CreationTime descending
                            select new SupplierDto
                            {
                                Code = suppliers.Code,
                                SName = suppliers.SName,
                                ContactName = suppliers.ContactName,
                                BeginTime = suppliers.BeginTime,
                                EndTime = suppliers.EndTime,
                                CreationTime = suppliers.CreationTime,
                                ContactNumber = suppliers.ContactNumber,

                            }).OrderByDescending(m => m.CreationTime).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();


                result.IsSuccess(new PagedList<SupplierDto>(list.Count, list));

            }
            catch (Exception ex)
            {
               _logger.LogError(ex.ToString());
                result.IsFailed("查询失败");
            }

            return result;
        }


        #region 订阅事件
        /// <summary>
        /// 订阅校验供应商事件
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        [NonAction]
        public async Task HandleEventAsync(OrderSupplicerEto eventData)
        {
            try
            {
                var entity = await _supplierRepository.FindAsync(x => x.Code == eventData.Code && x.IsDeleted == false);
                if (entity == null)
                {
                    throw new NotImplementedException("不存在该供应商");
                }
                else
                {
                    if (entity.EndTime != null && (DateTime.Compare((DateTime)entity.EndTime, DateTime.Now) < 0))
                    {
                        throw new NotImplementedException("该供应商已经过期");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new NotImplementedException(ex.ToString());
            }
        }

        ///// <summary>
        ///// 测试
        ///// </summary>
        ///// <param name="eventData"></param>
        ///// <returns></returns>
        //[NonAction]
        //public async Task HandleEventAsync(CheckOrderExistsEto eventData)
        //{
        //    await _supplierRepository.FindAsync(x => x.Id == 1);
        //    eventData.Order = null;
        //}
        #endregion

        #region 废弃
        ///// <summary>
        ///// 按名字分页查询
        ///// </summary>
        ///// <param name="input"></param>
        ///// <param name="name"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("SupplierListByName")]
        //public async Task<ServiceResult<PagedList<SupplierDto>>> GetSupplierListByNameAsync(PagingInput input, string name = "")
        //{
        //    var result = new ServiceResult<PagedList<SupplierDto>>();
        //    try
        //    {
        //        if (string.IsNullOrEmpty(name))
        //        {

        //            var list = _supplierRepository
        //                                  .Where(x => x.IsDeleted == false)
        //                                  .OrderByDescending(x => x.CreationTime)
        //                                  .PageByIndex(input.Page, input.Limit)
        //                                  .Select(x => new SupplierDto
        //                                  {
        //                                      Code = x.Code,
        //                                      SName = x.SName,
        //                                      ContactName = x.ContactName,
        //                                      BeginTime = x.BeginTime,
        //                                      EndTime = x.EndTime,
        //                                      CreationTime = x.CreationTime,
        //                                      ContactNumber = x.ContactNumber,
        //                                  })
        //                                  //.Select(x => ObjectMapper.Map<Supplier, SupplierDto>(x))
        //                                  .ToList();

        //            result.IsSuccess(new PagedList<SupplierDto>(list.Count, list));
        //        }
        //        else
        //        {
        //            var list = (from suppliers in await _supplierRepository.GetListAsync()
        //                        where suppliers.SName.Contains(name) && suppliers.IsDeleted == false
        //                        orderby suppliers.CreationTime descending
        //                        select new SupplierDto
        //                        {
        //                            Code = suppliers.Code,
        //                            SName = suppliers.SName,
        //                            ContactName = suppliers.ContactName,
        //                            BeginTime = suppliers.BeginTime,
        //                            EndTime = suppliers.EndTime,
        //                            CreationTime = suppliers.CreationTime,
        //                            ContactNumber = suppliers.ContactNumber,

        //                        }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //            result.IsSuccess(new PagedList<SupplierDto>(list.Count, list));
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //       _logger.LogError(ex.ToString());
        //        result.IsFailed("查询失败");
        //    }

        //    return result;
        //}
        ///// <summary>
        ///// 按编号分页查询
        ///// </summary>
        ///// <param name="input"></param>
        ///// <param name="code"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("SupplierListByCode")]
        //public async Task<ServiceResult<PagedList<SupplierDto>>> GetSupplierListByCodeAsync(PagingInput input, string code = "")
        //{
        //    var result = new ServiceResult<PagedList<SupplierDto>>();
        //    try
        //    {
        //        if (string.IsNullOrEmpty(code))
        //        {
        //            var list = _supplierRepository
        //                                  .Where(x => x.IsDeleted == false)
        //                                  .OrderByDescending(x => x.CreationTime)
        //                                  .PageByIndex(input.Page, input.Limit)
        //                                  .Select(x => new SupplierDto
        //                                  {
        //                                      Code = x.Code,
        //                                      SName = x.SName,
        //                                      ContactName = x.ContactName,
        //                                      BeginTime = x.BeginTime,
        //                                      EndTime = x.EndTime,
        //                                      CreationTime = x.CreationTime,
        //                                      ContactNumber = x.ContactNumber,
        //                                  })
        //                                  //.Select(x => ObjectMapper.Map<Supplier, SupplierDto>(x))
        //                                  .ToList();
        //            result.IsSuccess(new PagedList<SupplierDto>(list.Count, list));
        //        }
        //        else
        //        {
        //            var list = (from suppliers in await _supplierRepository.GetListAsync()
        //                        where suppliers.Code.Contains(code) && suppliers.IsDeleted == false
        //                        orderby suppliers.CreationTime descending
        //                        select new SupplierDto
        //                        {
        //                            Code = suppliers.Code,
        //                            SName = suppliers.SName,
        //                            ContactName = suppliers.ContactName,
        //                            BeginTime = suppliers.BeginTime,
        //                            EndTime = suppliers.EndTime,
        //                            CreationTime = suppliers.CreationTime,
        //                            ContactNumber = suppliers.ContactNumber,

        //                        }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //            result.IsSuccess(new PagedList<SupplierDto>(list.Count, list));
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //       _logger.LogError(ex.ToString());
        //        result.IsFailed("查询失败");
        //    }

        //    return result;
        //} 
        #endregion

    }
}
